import {
  type userType,
  type LoginTokenResult,
  type userInfoType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  getVerifyCode,
  getLogin,
  refreshTokenApi,
  getInfo,
  updateInfo
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { setToken, removeToken, userKey, getToken } from "@/utils/auth";
import { useSseClientStoreHook } from "./sseClient";
export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 头像
    avatar: storageLocal().getItem<LoginTokenResult>(userKey)?.avatar ?? "",
    // 用户名
    userName: storageLocal().getItem<LoginTokenResult>(userKey)?.userName ?? "",
    // 昵称
    nickName: storageLocal().getItem<LoginTokenResult>(userKey)?.nickName ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<LoginTokenResult>(userKey)?.roles ?? [],
    // 按钮级别权限
    permissions:
      storageLocal().getItem<LoginTokenResult>(userKey)?.permissions ?? [],
    // 前端生成的验证码（按实际需求替换）
    verifyCode: "",
    // 判断登录页面显示哪个组件（0：登录（默认）、1：手机登录、2：二维码登录、3：注册、4：忘记密码）
    currentPage: 0,
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(userName: string) {
      this.userName = userName;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickName: string) {
      this.nickName = nickName;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储前端生成的验证码 */
    SET_VERIFYCODE(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 获取svg验证码 */
    async initVerifyCodeImg() {
      return getVerifyCode();
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<LoginTokenResult>((resolve, reject) => {
        getLogin(data)
          .then(res => {
            setToken(res);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.userName = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      useSseClientStoreHook().disconnect();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken() {
      return new Promise<LoginTokenResult>(async (resolve, reject) => {
        refreshTokenApi({
          id: getToken().connectSid
        })
          .then(data => {
            setToken(data);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 获取用户信息 */
    getUserInfo() {
      return new Promise<userInfoType>(resolve => {
        getInfo().then(info => {
          // 其他操作
          resolve(info);
        });
      });
    },
    /** 修改用户信息 */
    updateUserInfo(data) {
      return new Promise((resolve, reject) => {
        updateInfo(data)
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
